﻿using System.Data.Odbc;
using System;

namespace personalplaner.business.common
{
	public class DatabaseSettings : IDisposable
	{
		#region IDisposable Members

		public void Dispose()
		{
			if (Connection == null)
				return;

			if (Connection.State != System.Data.ConnectionState.Closed)
			{
				try
				{
					Connection.Close();
				}
				catch
				{
				}
			}

			Connection.Dispose();
		}

		#endregion

		string _connectionString;
		/// <summary>
		/// "DSN="DSNName;UID=userid/sa;PWD=password;Database=database;"
		/// </summary>
		public string ConnetionString
		{
			get
			{
				return _connectionString;
			}
			set
			{
				_connectionString = value;

				if (string.IsNullOrEmpty(_connectionString))
					throw new PersonalplanerException("ConnectionString is not allowed to be null or empty");

				try
				{
					Connection = new OdbcConnection(ConnetionString);
					if (Timeout > 0)
						Connection.ConnectionTimeout = Timeout;
				}
				catch (OdbcException ex)
				{
					throw new PersonalplanerException("Conection object could not be set", ex);
				}
			}
		}

		/// <summary>
		/// OdbcConnection object
		/// </summary>
		public OdbcConnection Connection
		{
			get;
			set;
		}

		int _timeout = -1;
		public int Timeout
		{
			get
			{
				return _timeout;
			}
			set
			{
				_timeout = value;

				if (Connection != null)
					Connection.ConnectionTimeout = value;
			}
		}
	}
}
